package com.stone.bypass.proxy.core.config;

import com.stone.bypass.proxy.core.anno.ClassPathScanner;
import com.stone.bypass.proxy.core.anno.CreateDiversionProxy;
import com.stone.bypass.proxy.core.support.CreateDiversionProxyFactoryBean;
import java.util.LinkedHashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * @Auther: stone
 * @Date: 2021/3/7 22:55
 * @Description:
 */
public class CreateDiversionProxyRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar,
    ResourceLoaderAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(CreateDiversionProxyRegistrar.class);
    private BeanFactory beanFactory;
    private ResourceLoader resourceLoader;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
        BeanDefinitionRegistry registry) {

        LOGGER.debug("Searching for CreateDiversionProxy annotated with @CreateDiversionProxy");
        AnnotationAttributes attributes = AnnotationAttributes
            .fromMap(importingClassMetadata.getAnnotationAttributes(EnableCreateDiversionProxy.class.getName()));
        if (attributes == null) {
            return;
        }
        String[] packages = getPackagesToScan(attributes);
        ClassPathScanner scanner = new ClassPathScanner(registry);
        if (this.resourceLoader != null) {
            scanner.setResourceLoader(this.resourceLoader);
        }
        scanner.addIncludeFilter(new AnnotationTypeFilter(CreateDiversionProxy.class));
        Set<BeanDefinitionHolder> set = scanner.doScan(packages);
        processBeanDefinitions(set);
    }

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        if (CollectionUtils.isEmpty(beanDefinitions)) {
            return;
        }
        
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
            String beanClassName = definition.getBeanClassName();
            definition.getConstructorArgumentValues().addIndexedArgumentValue(0, beanClassName);
            definition.getConstructorArgumentValues().addIndexedArgumentValue(1, holder.getBeanName());
            definition.setBeanClass(CreateDiversionProxyFactoryBean.class);
            definition.setPrimary(true);
            definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        }
    }


    /**
     * 获取扫描的基础包路径
     *
     * @return 基础包路径
     */
    private String[] getPackagesToScan(AnnotationAttributes attributes) {
        Set<String> packagesToScan = new LinkedHashSet<>();
        for (String pkg : attributes.getStringArray("value")) {
            if (StringUtils.hasText(pkg)) {
                packagesToScan.add(pkg);
            }
        }

        for (String pkg : attributes.getStringArray("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                packagesToScan.add(pkg);
            }
        }

        for (Class<?> clazz : attributes.getClassArray("basePackageClasses")) {
            packagesToScan.add(ClassUtils.getPackageName(clazz));
        }
        if (packagesToScan.isEmpty()) {
            packagesToScan.addAll(AutoConfigurationPackages.get(beanFactory));
        }

        return packagesToScan.toArray(new String[0]);
    }
}
